const router = require("koa-router")();
const moment = require("moment");
const xlsx = require("node-xlsx");

/**
 * api {get} /home/app/schema/schema 模型列表
 *
 * apiParam {Number} page 页码
 * apiParam {String} name 数据表
 *
 */
router.get("/schema", async (ctx, nex) => {
  const user = ctx.user;
  const baas = ctx.baas;
  const { page, name } = ctx.query;

  const table = await BaaS.Models.table
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      if (name) {
        qb.where("name", "=", name);
      }
      qb.orderBy("id", "desc");
    })
    .fetchPage({
      pageSize: ctx.config("pageSize"),
      page: page,
      withRelated: []
    });

  ctx.success(table, "模型列表");
});
/**
 * api {get} /home/app/schema/info/schema 模型搜索
 *
 *
 */
router.get("/info/schema", async (ctx, nex) => {
  const user = ctx.user;
  const baas = ctx.baas;
  // 数据表
  const table = await ctx.table(baas.database); // 数据表

  const data = {
    table: table
  };

  ctx.success(data, "数据表字段");
});
/**
 * api {get} /home/app/schema/field/:tableName 查询表字段
 *
 *
 */
router.get("/schema/field/:tableName", async (ctx, nex) => {
  const baas = ctx.baas;
  const { tableName } = ctx.params;

  const sql =
    "show full fields from `" + baas.database + "`.`" + tableName + "`";
  const field = await ctx.bookshelf.knex.raw(sql);

  ctx.success(field[0], "数据表字段");
});
/**
 * api {get} /home/app/schema/export/schema 导出模型
 *
 * apiParam {String} name 数据表
 *
 */
router.get("/export/schema", async (ctx, nex) => {
  const baas = ctx.baas;
  const { name } = ctx.query;

  const tableList = await BaaS.Models.table
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      if (name) {
        qb.where("name", "=", name);
      }
      qb.orderBy("id", "desc");
    })
    .fetchAll();

  const rows = [];
  rows[0] = ["数据表", "uuid", "隐藏字段", "schema", "创建时间", "更新时间"];
  for (const key in tableList) {
    tableList[key].uuid = tableList[key].uuid ? "是" : "否";
    rows.push([
      tableList[key].name,
      tableList[key].uuid,
      tableList[key].hidden,
      tableList[key].schema,
      tableList[key].created_at,
      tableList[key].updated_at
    ]);
  }

  const fileName = moment().format("YYYY-MM-DD HH:mm:ss");
  const buffer = xlsx.build([
    {
      file_name: fileName,
      data: rows
    }
  ]);
  ctx.set("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
  ctx.body = buffer;
});

/**
 * api {get} /home/app/schema/schema/:id 获取单个模型
 *
 * apiParam {Number} id 关联表id
 *
 */
router.get("/schema/:id", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id } = ctx.params;

  const table = await BaaS.Models.table
    .query(qb => {
      qb.where("id", "=", id);
      qb.where("baas_id", "=", baas.id);
    })
    .fetch();

  ctx.success(table, "单个关联信息");
});
/**
 * api {post} /home/app/schema/add/schema 新增修改模型
 * 
 * apiParam {
	name: 数据表
	uuid: uuid
	hidden: 隐藏字段,逗号分隔
	unique: 隐藏字段,逗号分隔
	schema: schema
 } 
 * 
 */
router.post("/add/schema", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id, name, uuid, hidden, unique } = ctx.post;

  const table = await BaaS.Models.table
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.where("name", "=", name);
    })
    .fetch();
  if (table && table.id != id) {
    ctx.error("", "该模型已存在");
    return;
  }

  const result = await BaaS.Models.table
    .forge({
      id: id,
      baas_id: baas.id,
      name: name,
      uuid: uuid,
      hidden: hidden,
      unique: unique
    })
    .save();

  // 删除redis缓存
  await BaaS.redis.delAll(
    `baas:*:appid:${baas.appid}:appkey:${baas.appkey}:tables`
  );

  ctx.success(result, "保存成功");
});
/**
 * api {get} /home/app/schema/del/schema/:id 删除关联
 *
 * apiParam {Number} id 关联表id
 *
 */
router.get("/del/schema/:id", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id } = ctx.params;

  const table = await BaaS.Models.table
    .query(qb => {
      qb.where("id", "=", id);
      qb.where("baas_id", "=", baas.id);
    })
    .fetch();
  if (!table) {
    ctx.error("", "参数错误");
    return;
  }

  const result = await BaaS.Models.table
    .forge({
      id: id
    })
    .destroy();

  // 删除redis缓存
  await BaaS.redis.delAll(
    `baas:*:appid:${baas.appid}:appkey:${baas.appkey}:tables`
  );

  ctx.success(result, "删除关联");
});

module.exports = router;
